import * as vscode from 'vscode';

/**
 * 镜像偏好设置管理器
 * 处理用户偏好设置的读取和写入
 */
export class MirrorPreferenceManager {
    private readonly connectPrefKey = 'magicApi.mirror.connectPreference';

    // 读取/写入镜像连接偏好（按文件夹路径存储，范围：全局用户）
    public async getMirrorConnectPreference(root: vscode.Uri): Promise<'yes' | 'no' | undefined> {
        const map = this.context.globalState.get<Record<string, 'yes' | 'no'>>(this.connectPrefKey) || {};
        return map[root.fsPath];
    }

    public async setMirrorConnectPreference(root: vscode.Uri, pref: 'yes' | 'no'): Promise<void> {
        const map = this.context.globalState.get<Record<string, 'yes' | 'no'>>(this.connectPrefKey) || {};
        map[root.fsPath] = pref;
        await this.context.globalState.update(this.connectPrefKey, map);
    }

    // 获取默认镜像根目录（基于服务器 URL 生成稳定目录名）
    public getDefaultMirrorRoot(serverConfig: MagicServerConfig): vscode.Uri {
        const url = serverConfig.url || 'unknown';
        // 目录名：去除协议和末尾斜杠，替换非法字符
        const name = url.replace(/^[a-zA-Z]+:\/\//, '')
            .replace(/\/$/, '')
            .replace(/[^a-zA-Z0-9._-]/g, '_');
        const base = vscode.Uri.joinPath(this.context.globalStorageUri, 'magic-api-mirror', name);
        return base;
    }

    constructor(private context: vscode.ExtensionContext) {}
}

// 临时类型定义
interface MagicServerConfig {
    url?: string;
    token?: string;
    username?: string;
    password?: string;
}